<?php
namespace app\backend\controller;

use app\backend\model\Stage as StageModel;
use app\backend\model\Other as OtherModel;
use think\Db;
use think\Request;
use app\backend\org\Image;

class Images extends Base
{
     static function traverse($path = '.') {
        $current_dir = opendir($path);    //opendir()返回一个目录句柄,失败返回false
        while(($file = readdir($current_dir)) !== false) {    //readdir()返回打开目录句柄中的一个条目
            $sub_dir = $path . DIRECTORY_SEPARATOR . $file;    //构建子目录路径
            if($file == '.' || $file == '..') {
                continue;
            } else if(is_dir($sub_dir)) {    //如果是目录,进行递归
                echo 'Directory ' . $file . ':<br>';
                traverse($sub_dir);
            } else {    //如果是文件,直接输出
                echo 'File in Directory ' . $path . ': ' . $file . '<br>';
            }
        }
    }
    public function index($page=1)
    {
        $file_ex = "{$_SERVER['DOCUMENT_ROOT']}/static/file_exist.txt";
        if(file_exists($file_ex)){
           $array_file =  json_decode(file_get_contents($file_ex));
        }else{
            $dir="{$_SERVER['DOCUMENT_ROOT']}/static/img/news"; //这里输入其它路径
            $url = "/static/img/news/";
            //PHP遍历文件夹下所有文件

            $handle=opendir($dir);
            //print_r($handle);exit;
            $array_file = array();
            $array_time = array();
            while (false !== ($file = readdir($handle)))
            {
                if ($file != "." && $file != "..") {
                    // $array_file[] = $url.$file; //输出文件名
                    //$array_file[] = ["filr_name"=>$url.$file, "file_time"=>filectime($url.$file)];
                    $array_file[] = $url.$file;
                    $array_time[] = filemtime($dir."/".$file);
                }
            }
            array_multisort($array_time,SORT_DESC,
                            $array_file);
            /*var_dump($array_time);
            var_dump($array_file);exit;*/
            file_put_contents($file_ex,json_encode($array_file));
        }
//exit;

        //每页显示多少行
        $psize = 10;
        //计算文件总数
        $filecount =  count($array_file);
        //总页数
        $pages = intval($filecount/ $psize);
        //开始位置
        $startIndex=($page-1)* $psize;
        //判断分页书否超过
        if($startIndex>=count($array_file)){
            $startIndex= $pages* $psize;
        }
        $array = array_slice($array_file,$startIndex, $psize,true);
        //$url_name = array();
        //新数组存放变量
        $array_img = array();
        foreach ($array as $k=>$v){
           // $url_name[] =
            $array_img[$k]["url_name"]= substr($v,strrpos("{$v}","/")+1);
            $array_img[$k]["image"]=$v;
        }
        $curr_page = $page;
       // var_dump($array_img);exit;
        if($page==1){
            $page=2;
        }

//遍历指定文件目录与文件数量结束
//var_dump($page);exit;
        //分配图片名称用于删除
        //$this->assign('url',$url_name);
        $this->assign('page',$page);
        $this->assign('curr_page',$curr_page);
        $this->assign('pages',$pages);
        $this->assign('data_img',$array);
        $this->assign('images',$array_img);
        $this->assign('empty',"暂无数据");
        //$this->assign('act','index');//高亮js
        return $this->fetch();

    }



    public function img_create(){
        if (Request::instance()->isPost()) {
                // 获取表单上传文件 例如上传了001.jpg
                $files = request()->file('image');
//                echo "<pre>";
//                print_r($files);exit;
                $images = array();
                $fail = array();
                $path = "/static/img/news";
                if (!empty($files)) {

                    foreach ($files as $file) {
                        //print_r($file->getInfo()["name"]);exit;
                        // 移动到框架应用根目录/public/static/img/news/ 目录下
                        $info = $file->validate(['ext' => 'jpg,png,gif,jpeg,bmp,tiff,svg'])->rule('uniqid')->move(ROOT_PATH . 'public' . $path, true, false);
                        if ($info) {
                            // 输出 20160820/42a79759f284b767dfcb2a0197904287.jpg
                            //$path =  $info->getExtension();
                            // 成功上传后 返回上传信息
                            //echo $info->getFilename();
                            $images[] = $path . "/" . $info->getFilename();
                        }else{
                            $fail[] = $file->getInfo()["name"];
                        }
                    }
                    //更新txt文件
                    $file_ex = "{$_SERVER['DOCUMENT_ROOT']}/static/file_exist.txt";
                    $dir="{$_SERVER['DOCUMENT_ROOT']}/static/img/news"; //这里输入其它路径
                    $url = "/static/img/news/";
                    //PHP遍历文件夹下所有文件
                    $handle=opendir($dir);
                    $array_file = array();
                    $array_time = array();
                    while (false !== ($file = readdir($handle)))
                    {
                        if ($file != "." && $file != "..") {
                            // $array_file[] = $url.$file; //输出文件名
                            //$array_file[] = ["filr_name"=>$url.$file, "file_time"=>filectime($url.$file)];
                            $array_file[] = $url.$file;
                            $array_time[] = filemtime($dir."/".$file);
                        }
                    }
                    array_multisort($array_time,SORT_DESC,
                        $array_file);
                    /*var_dump($array_time);
                    var_dump($array_file);exit;*/
                    file_put_contents($file_ex,json_encode($array_file));
                    //echo 123;exit;
                    if($fail){
                        $this->assign('fail',$fail);
                        return $this->fetch("images/error");
                    }
                    $this->success('上传成功', url('images/index'));
                }
        }
        return $this->fetch();
    }

    public function error1(){
        $this->assign('fail',["123"]);
        return $this->fetch("images/error");
    }

    //删除部门  软删除，记录删除时间
    public function img_delete($url_name)
    {
        //$id = Request::instance()->param("id");
        //$file =$url; //substr($id,strrpos("{$id}","/")+1);
        $path = "{$_SERVER['DOCUMENT_ROOT']}/static/img/news";
        $file = $path."/".$url_name;
        //var_dump($file);exit;
        $result = @unlink ($file);
        if ($result == false) {
            $this->redirect('images/index');
        } else {
            $this->error("删除失败");
        }

        return $this->fetch();
    }

}